#include <buola/chart/clegend.h>

#include <buola/image/cgc.h>

namespace buola { namespace chart {

CLegend::CLegend()
{
}

CLegend::~CLegend()
{
}

void CLegend::Draw(img::CGC *pGC,const CRect_d &pRect,PPlot pHL)
{
    CSize_d lMaxSize(0,0);
    
    for(int i=0;i<mItems.size();i++)
    {
        CSize_d lTextSize=pGC->GetTextExtents(mItems[i]->mText);

        lMaxSize.x=max(lMaxSize.x,lTextSize.x);
        lMaxSize.y=max(lMaxSize.y,lTextSize.y);
    }

    lMaxSize.y+=10;
    CSize_d lLegendSize(lMaxSize.x+lMaxSize.y+20,mItems.size()*lMaxSize.y+20);
    CPoint_d lLegendPos(pRect.r-lLegendSize.x-20,pRect.t+20);

    mRect={lLegendPos,lLegendSize};

    pGC->Path().Rect(lLegendPos,lLegendSize);
    pGC->SetSource(img::CColor(0.4,0.4,0.4,0.4));
    pGC->FillPath(true);
    pGC->SetSource(img::CColor(0,0,0,0.85));
    pGC->StrokePath();

    CPoint_d lPoint(lLegendPos.x+10,lLegendPos.y+10);

    for(int i=0;i<mItems.size();i++)
    {
        mItems[i]->mPos=lPoint;

        pGC->Path().Rect(CPoint_d(lPoint.x,lPoint.y+5),
                        CSize_d(lMaxSize.y-10,lMaxSize.y-10));

        if(!(mItems[i]->mStyle&CPlot::DISABLED))
        {
            pGC->SetSource(mItems[i]->mColor);
            pGC->FillPath(true);
            pGC->SetSource(img::CColor(0,0,0));
        }
        else
        {
            pGC->SetSource(img::CColor(0.4,0.4,0.4));
        }

        pGC->StrokePath();
        
        pGC->DrawText(CPoint_d(lPoint.x+lMaxSize.y,lPoint.y+lMaxSize.y/2),mItems[i]->mText,img::ETextPos::VCENTER);
        if(mItems[i]->mPlot==pHL)
        {
            pGC->DrawText(CPoint_d(lPoint.x+lMaxSize.y+1,lPoint.y+lMaxSize.y/2),
                          mItems[i]->mText,img::ETextPos::VCENTER);
        }
        lPoint.y+=lMaxSize.y;
    }
}

bool CLegend::Contains(const CPoint_d &pPoint)
{
    return mRect.Contains(pPoint);
}

PPlot CLegend::HitTest(const CPoint_d &pPoint)
{
    for(int i=0;i<mItems.size();i++)
    {
        if(CRect_d(mItems[i]->mPos,CSize_d(20,20)).Contains(pPoint))
            return mItems[i]->mPlot;
    }
    
    return nullptr;
}

void CLegend::AddItem(const SItem &pItem)
{
    mItems.emplace_back(new SItem(pItem));
}

void CLegend::ClearItems()
{
    mItems.clear();
}

/*namespace chart*/ } /*namespace buola*/ }
